package cn.iocoder.yudao.module.system.service.examscore;

import cn.iocoder.yudao.module.system.controller.admin.examscore.vo.NewExamScoreImportExcelVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

/**
 * 动态数据行解析器
 * 使用表头映射来灵活解析数据行
 */
@Component
@Slf4j
public class DynamicDataRowParser {

    /**
     * 使用动态表头映射解析数据行
     */
    public NewExamScoreImportExcelVO parseDataRow(Row dataRow, DynamicHeaderParser.HeaderMapping headerMapping) {
        if (dataRow == null || headerMapping == null) {
            return null;
        }
        
        NewExamScoreImportExcelVO importData = new NewExamScoreImportExcelVO();
        
        try {
            // 解析基础信息
            parseBasicInfo(dataRow, headerMapping, importData);
            
            // 解析总分信息
            parseTotalScores(dataRow, headerMapping, importData);
            
            // 解析各科目成绩
            parseSubjectScores(dataRow, headerMapping, importData);
            
            // 解析第一高分和第二高分
            parseTopScores(dataRow, headerMapping, importData);
            
            // 设置非计分科目信息
            setNonScoringSubjects(headerMapping, importData);
            
            log.debug("成功解析学生数据: {}", importData.getStudentName());
            return importData;
            
        } catch (Exception e) {
            log.error("解析数据行失败: 行{}, 错误: {}", dataRow.getRowNum(), e.getMessage(), e);
            return null;
        }
    }
    
    /**
     * 解析基础信息
     */
    private void parseBasicInfo(Row dataRow, DynamicHeaderParser.HeaderMapping headerMapping, 
                               NewExamScoreImportExcelVO importData) {
        importData.setExamNo(getCellStringValue(dataRow, headerMapping, "examNo"));
        importData.setStudentName(getCellStringValue(dataRow, headerMapping, "studentName"));
        importData.setClassName(getCellStringValue(dataRow, headerMapping, "className"));
        importData.setSubjectCombination(getCellStringValue(dataRow, headerMapping, "subjectCombination"));
    }
    
    /**
     * 解析总分信息
     */
    private void parseTotalScores(Row dataRow, DynamicHeaderParser.HeaderMapping headerMapping, 
                                 NewExamScoreImportExcelVO importData) {
        importData.setTotalOriginalScore(getCellBigDecimalValue(dataRow, headerMapping, "totalOriginalScore"));
        importData.setTotalAssignedScore(getCellBigDecimalValue(dataRow, headerMapping, "totalAssignedScore"));
        importData.setTotalUnionRank(getCellIntegerValue(dataRow, headerMapping, "totalUnionRank"));
        importData.setCombinationRank(getCellIntegerValue(dataRow, headerMapping, "combinationRank"));
        importData.setSchoolRank(getCellIntegerValue(dataRow, headerMapping, "schoolRank"));
        importData.setClassRank(getCellIntegerValue(dataRow, headerMapping, "classRank"));
    }
    
    /**
     * 解析各科目成绩
     */
    private void parseSubjectScores(Row dataRow, DynamicHeaderParser.HeaderMapping headerMapping, 
                                   NewExamScoreImportExcelVO importData) {
        // 语文
        parseSubjectScore(dataRow, headerMapping, importData, "chinese", 
            (score, rank1, rank2, rank3, assigned, level) -> {
                importData.setChineseOriginalScore(score);
                importData.setChineseUnionRank(rank1);
                importData.setChineseSchoolRank(rank2);
                importData.setChineseClassRank(rank3);
            });
        
        // 数学
        parseSubjectScore(dataRow, headerMapping, importData, "math", 
            (score, rank1, rank2, rank3, assigned, level) -> {
                importData.setMathOriginalScore(score);
                importData.setMathUnionRank(rank1);
                importData.setMathSchoolRank(rank2);
                importData.setMathClassRank(rank3);
            });
        
        // 英语
        parseSubjectScore(dataRow, headerMapping, importData, "english", 
            (score, rank1, rank2, rank3, assigned, level) -> {
                importData.setEnglishOriginalScore(score);
                importData.setEnglishUnionRank(rank1);
                importData.setEnglishSchoolRank(rank2);
                importData.setEnglishClassRank(rank3);
                
                // 调试：输出英语成绩解析结果
                if (score == null && rank1 == null && rank2 == null && rank3 == null) {
                    Integer englishColumn = headerMapping.getColumnIndex("englishOriginalScore");
                    log.warn("英语成绩全部为空：列索引={}, 学生={}", englishColumn, importData.getStudentName());
                }
            });
        
        String tableType = headerMapping.getTableType();
        boolean comboEmpty = importData.getSubjectCombination() == null || importData.getSubjectCombination().trim().isEmpty();
        if (comboEmpty) {
            parseSubjectScore(dataRow, headerMapping, importData, "physics",
                (score, rank1, rank2, rank3, assigned, level) -> {
                    importData.setPhysicsOriginalScore(score);
                    importData.setPhysicsUnionRank(rank1);
                    importData.setPhysicsSchoolRank(rank2);
                    importData.setPhysicsClassRank(rank3);
                });
            parseSubjectScore(dataRow, headerMapping, importData, "history",
                (score, rank1, rank2, rank3, assigned, level) -> {
                    importData.setHistoryOriginalScore(score);
                    importData.setHistoryUnionRank(rank1);
                    importData.setHistorySchoolRank(rank2);
                    importData.setHistoryClassRank(rank3);
                });
        } else {
            if ("PHYSICS".equals(tableType)) {
                parseSubjectScore(dataRow, headerMapping, importData, "physics",
                    (score, rank1, rank2, rank3, assigned, level) -> {
                        importData.setPhysicsOriginalScore(score);
                        importData.setPhysicsUnionRank(rank1);
                        importData.setPhysicsSchoolRank(rank2);
                        importData.setPhysicsClassRank(rank3);
                    });
            } else if ("HISTORY".equals(tableType)) {
                parseSubjectScore(dataRow, headerMapping, importData, "history",
                    (score, rank1, rank2, rank3, assigned, level) -> {
                        importData.setHistoryOriginalScore(score);
                        importData.setHistoryUnionRank(rank1);
                        importData.setHistorySchoolRank(rank2);
                        importData.setHistoryClassRank(rank3);
                    });
            }
        }
        
        // 化学
        parseSubjectScore(dataRow, headerMapping, importData, "chemistry", 
            (score, rank1, rank2, rank3, assigned, level) -> {
                importData.setChemistryOriginalScore(score);
                importData.setChemistryAssignedScore(assigned);
                importData.setChemistryGradeLevel(level);
                importData.setChemistryUnionRank(rank1);
                importData.setChemistrySchoolRank(rank2);
                importData.setChemistryClassRank(rank3);
            });
        
        // 生物
        parseSubjectScore(dataRow, headerMapping, importData, "biology", 
            (score, rank1, rank2, rank3, assigned, level) -> {
                importData.setBiologyOriginalScore(score);
                importData.setBiologyAssignedScore(assigned);
                importData.setBiologyGradeLevel(level);
                importData.setBiologyUnionRank(rank1);
                importData.setBiologySchoolRank(rank2);
                importData.setBiologyClassRank(rank3);
            });
        
        // 政治
        parseSubjectScore(dataRow, headerMapping, importData, "politics", 
            (score, rank1, rank2, rank3, assigned, level) -> {
                importData.setPoliticsOriginalScore(score);
                importData.setPoliticsAssignedScore(assigned);
                importData.setPoliticsGradeLevel(level);
                importData.setPoliticsUnionRank(rank1);
                importData.setPoliticsSchoolRank(rank2);
                importData.setPoliticsClassRank(rank3);
            });
        
        // 地理
        parseSubjectScore(dataRow, headerMapping, importData, "geography", 
            (score, rank1, rank2, rank3, assigned, level) -> {
                importData.setGeographyOriginalScore(score);
                importData.setGeographyAssignedScore(assigned);
                importData.setGeographyGradeLevel(level);
                importData.setGeographyUnionRank(rank1);
                importData.setGeographySchoolRank(rank2);
                importData.setGeographyClassRank(rank3);
            });
        
        // 新增外语科目
        parseSubjectScore(dataRow, headerMapping, importData, "russian", 
            (score, rank1, rank2, rank3, assigned, level) -> {
                importData.setRussianOriginalScore(score);
                importData.setRussianAssignedScore(assigned);
                importData.setRussianGradeLevel(level);
                importData.setRussianUnionRank(rank1);
                importData.setRussianSchoolRank(rank2);
                importData.setRussianClassRank(rank3);
            });
        
        parseSubjectScore(dataRow, headerMapping, importData, "japanese", 
            (score, rank1, rank2, rank3, assigned, level) -> {
                importData.setJapaneseOriginalScore(score);
                importData.setJapaneseAssignedScore(assigned);
                importData.setJapaneseGradeLevel(level);
                importData.setJapaneseUnionRank(rank1);
                importData.setJapaneseSchoolRank(rank2);
                importData.setJapaneseClassRank(rank3);
            });
        
        parseSubjectScore(dataRow, headerMapping, importData, "spanish", 
            (score, rank1, rank2, rank3, assigned, level) -> {
                importData.setSpanishOriginalScore(score);
                importData.setSpanishAssignedScore(assigned);
                importData.setSpanishGradeLevel(level);
                importData.setSpanishUnionRank(rank1);
                importData.setSpanishSchoolRank(rank2);
                importData.setSpanishClassRank(rank3);
            });
    }
    
    /**
     * 解析单个科目成绩
     */
    private void parseSubjectScore(Row dataRow, DynamicHeaderParser.HeaderMapping headerMapping, 
                                  NewExamScoreImportExcelVO importData, String subjectPrefix,
                                  SubjectScoreSetter setter) {
        BigDecimal originalScore = getCellBigDecimalValue(dataRow, headerMapping, subjectPrefix + "OriginalScore");
        BigDecimal assignedScore = getCellBigDecimalValue(dataRow, headerMapping, subjectPrefix + "AssignedScore");
        String gradeLevel = getCellStringValue(dataRow, headerMapping, subjectPrefix + "GradeLevel");
        Integer unionRank = getCellIntegerValue(dataRow, headerMapping, subjectPrefix + "UnionRank");
        Integer schoolRank = getCellIntegerValue(dataRow, headerMapping, subjectPrefix + "SchoolRank");
        Integer classRank = getCellIntegerValue(dataRow, headerMapping, subjectPrefix + "ClassRank");
        
        // 添加小语种调试日志
//        if (subjectPrefix.equals("russian") || subjectPrefix.equals("japanese") || subjectPrefix.equals("spanish")) {
//            log.info("解析小语种数据: 科目={}, 原始分={}, 赋分={}, 等级={}, 联考排名={}, 校内排名={}, 班级排名={}",
//                subjectPrefix, originalScore, assignedScore, gradeLevel, unionRank, schoolRank, classRank);
//        }
        
        setter.setScores(originalScore, unionRank, schoolRank, classRank, assignedScore, gradeLevel);
    }
    
    /**
     * 科目成绩设置器接口
     */
    @FunctionalInterface
    private interface SubjectScoreSetter {
        void setScores(BigDecimal originalScore, Integer unionRank, Integer schoolRank, 
                      Integer classRank, BigDecimal assignedScore, String gradeLevel);
    }
    
    /**
     * 解析第一高分和第二高分
     */
    private void parseTopScores(Row dataRow, DynamicHeaderParser.HeaderMapping headerMapping, 
                               NewExamScoreImportExcelVO importData) {
        // 第一高分
        importData.setFirstTopSubject(getCellStringValue(dataRow, headerMapping, "firstTopSubject"));
        importData.setFirstTopOriginalScore(getCellBigDecimalValue(dataRow, headerMapping, "firstTopOriginalScore"));
        importData.setFirstTopAssignedScore(getCellBigDecimalValue(dataRow, headerMapping, "firstTopAssignedScore"));
        importData.setFirstTopUnionRank(getCellIntegerValue(dataRow, headerMapping, "firstTopUnionRank"));
        importData.setFirstTopSchoolRank(getCellIntegerValue(dataRow, headerMapping, "firstTopSchoolRank"));
        importData.setFirstTopClassRank(getCellIntegerValue(dataRow, headerMapping, "firstTopClassRank"));
        
        // 第二高分
        importData.setSecondTopSubject(getCellStringValue(dataRow, headerMapping, "secondTopSubject"));
        importData.setSecondTopOriginalScore(getCellBigDecimalValue(dataRow, headerMapping, "secondTopOriginalScore"));
        importData.setSecondTopAssignedScore(getCellBigDecimalValue(dataRow, headerMapping, "secondTopAssignedScore"));
        importData.setSecondTopUnionRank(getCellIntegerValue(dataRow, headerMapping, "secondTopUnionRank"));
        importData.setSecondTopSchoolRank(getCellIntegerValue(dataRow, headerMapping, "secondTopSchoolRank"));
        importData.setSecondTopClassRank(getCellIntegerValue(dataRow, headerMapping, "secondTopClassRank"));
    }
    
    /**
     * 设置非计分科目信息
     */
    private void setNonScoringSubjects(DynamicHeaderParser.HeaderMapping headerMapping, 
                                      NewExamScoreImportExcelVO importData) {
        if (!headerMapping.getNonScoringSubjects().isEmpty()) {
            StringJoiner joiner = new StringJoiner(",");
            for (String subject : headerMapping.getNonScoringSubjects()) {
                joiner.add(subject);
            }
            importData.setNonScoringSubjects(joiner.toString());
        }
    }
    
    /**
     * 获取单元格字符串值
     */
    private String getCellStringValue(Row dataRow, DynamicHeaderParser.HeaderMapping headerMapping, String fieldName) {
        Integer columnIndex = headerMapping.getColumnIndex(fieldName);
        if (columnIndex == null || columnIndex < 0) {
            return null;
        }
        
        Cell cell = dataRow.getCell(columnIndex);
        if (cell == null) {
            return null;
        }
        
        try {
            switch (cell.getCellType()) {
                case STRING:
                    return cell.getStringCellValue();
                case NUMERIC:
                    return String.valueOf((long) cell.getNumericCellValue());
                case BOOLEAN:
                    return String.valueOf(cell.getBooleanCellValue());
                case FORMULA:
                    return cell.getCellFormula();
                default:
                    return null;
            }
        } catch (Exception e) {
            log.warn("读取字符串值失败: 字段{}, 列{}, 错误: {}", fieldName, columnIndex, e.getMessage());
            return null;
        }
    }
    
    /**
     * 获取单元格BigDecimal值
     * 处理特殊值："-"、"未扫"、"不计排名"、"缺考"等视为null
     */
    private BigDecimal getCellBigDecimalValue(Row dataRow, DynamicHeaderParser.HeaderMapping headerMapping, String fieldName) {
        Integer columnIndex = headerMapping.getColumnIndex(fieldName);
        if (columnIndex == null || columnIndex < 0) {
            return null;
        }
        
        Cell cell = dataRow.getCell(columnIndex);
        if (cell == null) {
            return null;
        }
        
        try {
            switch (cell.getCellType()) {
                case NUMERIC:
                    return BigDecimal.valueOf(cell.getNumericCellValue());
                case STRING:
                    String stringValue = cell.getStringCellValue();
                    if (stringValue == null || stringValue.trim().isEmpty()) {
                        return null;
                    }
                    
                    stringValue = stringValue.trim();
                    
                    // 处理特殊值："-"、"未扫"、"不计排名"、"缺考"等视为null
                    if (stringValue.equals("-") || 
                        stringValue.equals("—") ||
                        stringValue.equals("－") ||
                        stringValue.contains("未扫") || 
                        stringValue.contains("不计排名") || 
                        stringValue.contains("缺考") ||
                        stringValue.contains("缺席")) {
                        return null;
                    }
                    
                    // 尝试解析数字
                    return new BigDecimal(stringValue);
                case FORMULA:
                    return BigDecimal.valueOf(cell.getNumericCellValue());
                default:
                    return null;
            }
        } catch (Exception e) {
            log.warn("读取BigDecimal值失败: 字段{}, 列{}, 错误: {}", fieldName, columnIndex, e.getMessage());
            return null;
        }
    }
    
    /**
     * 获取单元格Integer值
     * 处理特殊值："-"、"未扫"、"不计排名"等视为null
     */
    private Integer getCellIntegerValue(Row dataRow, DynamicHeaderParser.HeaderMapping headerMapping, String fieldName) {
        Integer columnIndex = headerMapping.getColumnIndex(fieldName);
        if (columnIndex == null || columnIndex < 0) {
            return null;
        }
        
        Cell cell = dataRow.getCell(columnIndex);
        if (cell == null) {
            return null;
        }
        
        try {
            switch (cell.getCellType()) {
                case NUMERIC:
                    return (int) cell.getNumericCellValue();
                case STRING:
                    String stringValue = cell.getStringCellValue();
                    if (stringValue == null || stringValue.trim().isEmpty()) {
                        return null;
                    }
                    
                    stringValue = stringValue.trim();
                    
                    // 处理特殊值："-"、"未扫"、"不计排名"等视为null
                    if (stringValue.equals("-") || 
                        stringValue.equals("—") ||
                        stringValue.equals("－") ||
                        stringValue.contains("未扫") || 
                        stringValue.contains("不计排名") || 
                        stringValue.contains("缺考") ||
                        stringValue.contains("缺席")) {
                        return null;
                    }
                    
                    return Integer.parseInt(stringValue);
                case FORMULA:
                    return (int) cell.getNumericCellValue();
                default:
                    return null;
            }
        } catch (Exception e) {
            log.warn("读取Integer值失败: 字段{}, 列{}, 错误: {}", fieldName, columnIndex, e.getMessage());
            return null;
        }
    }
    
    /**
     * 验证解析后的数据完整性和正确性
     */
    public DataValidationResult validateParsedData(NewExamScoreImportExcelVO importData, 
                                                   DynamicHeaderParser.HeaderMapping headerMapping) {
        DataValidationResult result = new DataValidationResult();
        
        if (importData == null) {
            result.addError("导入数据为空");
            return result;
        }
        
        // 1. 验证基础信息
        validateBasicInfo(importData, result);
        
        // 2. 验证总分信息
        validateTotalScores(importData, result);
        
        // 3. 验证科目成绩
        validateSubjectScores(importData, result);
        
        // 4. 验证排名信息
        validateRankings(importData, result);
        
        // 5. 验证数据一致性
        validateDataConsistency(importData, result);
        
        return result;
    }
    
    /**
     * 验证基础信息
     */
    private void validateBasicInfo(NewExamScoreImportExcelVO importData, DataValidationResult result) {
        // 验证学生姓名
        if (importData.getStudentName() == null || importData.getStudentName().trim().isEmpty()) {
            result.addError("学生姓名不能为空");
        } else if (!importData.getStudentName().matches("^[\\u4e00-\\u9fa5]{2,10}$")) {
            result.addWarning("学生姓名格式可能不正确: " + importData.getStudentName());
        }
        
        // 验证考号（可选字段，某些学校可能不使用考号）
        if (importData.getExamNo() == null || importData.getExamNo().trim().isEmpty()) {
            result.addInfo("考号为空");
        } else if (!importData.getExamNo().matches("^[0-9A-Za-z]+$")) {
            result.addWarning("考号格式可能不正确: " + importData.getExamNo());
        }
        
        // 验证班级名称
        if (importData.getClassName() == null || importData.getClassName().trim().isEmpty()) {
            result.addError("班级名称不能为空");
        }
        
        // 验证选科组合（可选字段，高一年级可能没有选科）
        if (importData.getSubjectCombination() == null || importData.getSubjectCombination().trim().isEmpty()) {
            result.addInfo("选科组合为空，可能是高一年级或未选科学生");
        }
    }
    
    /**
     * 验证总分信息
     */
    private void validateTotalScores(NewExamScoreImportExcelVO importData, DataValidationResult result) {
        BigDecimal originalTotal = importData.getTotalOriginalScore();
        BigDecimal assignedTotal = importData.getTotalAssignedScore();
        
        // 验证总分范围
        if (originalTotal != null) {
            if (originalTotal.compareTo(BigDecimal.ZERO) < 0) {
                result.addError("原始总分不能为负数: " + originalTotal);
            } else if (originalTotal.compareTo(new BigDecimal("1000")) > 0) {
                result.addWarning("原始总分异常高: " + originalTotal);
            }
        }
        
        if (assignedTotal != null) {
            if (assignedTotal.compareTo(BigDecimal.ZERO) < 0) {
                result.addError("赋分总分不能为负数: " + assignedTotal);
            } else if (assignedTotal.compareTo(new BigDecimal("1000")) > 0) {
                result.addWarning("赋分总分异常高: " + assignedTotal);
            }
        }
        
        // 验证总分一致性
        if (originalTotal != null && assignedTotal != null) {
            BigDecimal difference = originalTotal.subtract(assignedTotal).abs();
            if (difference.compareTo(new BigDecimal("200")) > 0) {
                result.addWarning("原始总分与赋分总分差异较大: " + difference);
            }
        }
    }
    
    /**
     * 验证科目成绩
     */
    private void validateSubjectScores(NewExamScoreImportExcelVO importData, DataValidationResult result) {
        // 验证各科目成绩范围
        validateSubjectScore("语文", importData.getChineseOriginalScore(), null, result);
        validateSubjectScore("数学", importData.getMathOriginalScore(), null, result);
        validateSubjectScore("英语", importData.getEnglishOriginalScore(), null, result);
        validateSubjectScore("物理", importData.getPhysicsOriginalScore(), null, result);
        validateSubjectScore("化学", importData.getChemistryOriginalScore(), importData.getChemistryAssignedScore(), result);
        validateSubjectScore("生物", importData.getBiologyOriginalScore(), importData.getBiologyAssignedScore(), result);
        validateSubjectScore("历史", importData.getHistoryOriginalScore(), importData.getHistoryAssignedScore(), result);
        validateSubjectScore("地理", importData.getGeographyOriginalScore(), importData.getGeographyAssignedScore(), result);
        validateSubjectScore("政治", importData.getPoliticsOriginalScore(), importData.getPoliticsAssignedScore(), result);
        
        // 验证外语科目
        validateSubjectScore("俄语", importData.getRussianOriginalScore(), importData.getRussianAssignedScore(), result);
        validateSubjectScore("日语", importData.getJapaneseOriginalScore(), importData.getJapaneseAssignedScore(), result);
        validateSubjectScore("西班牙语", importData.getSpanishOriginalScore(), importData.getSpanishAssignedScore(), result);
    }
    
    /**
     * 验证单个科目成绩
     */
    private void validateSubjectScore(String subjectName, BigDecimal originalScore, BigDecimal assignedScore, 
                                     DataValidationResult result) {
        if (originalScore != null) {
            if (originalScore.compareTo(BigDecimal.ZERO) < 0) {
                result.addError(subjectName + "原始成绩不能为负数: " + originalScore);
            } else if (originalScore.compareTo(new BigDecimal("150")) > 0) {
                result.addWarning(subjectName + "原始成绩异常高: " + originalScore);
            }
        }
        
        if (assignedScore != null) {
            if (assignedScore.compareTo(BigDecimal.ZERO) < 0) {
                result.addError(subjectName + "赋分成绩不能为负数: " + assignedScore);
            } else if (assignedScore.compareTo(new BigDecimal("100")) > 0) {
                result.addWarning(subjectName + "赋分成绩异常高: " + assignedScore);
            }
        }
    }
    
    /**
     * 验证排名信息
     */
    private void validateRankings(NewExamScoreImportExcelVO importData, DataValidationResult result) {
        // 验证总分排名
        validateRanking("联考总分排名", importData.getTotalUnionRank(), result);
        validateRanking("校内总分排名", importData.getSchoolRank(), result);
        validateRanking("班内总分排名", importData.getClassRank(), result);
        
        // 验证排名逻辑关系
        if (importData.getTotalUnionRank() != null && importData.getSchoolRank() != null) {
            if (importData.getTotalUnionRank() > importData.getSchoolRank()) {
                result.addWarning("联考排名应该大于等于校内排名");
            }
        }
        
        if (importData.getSchoolRank() != null && importData.getClassRank() != null) {
            if (importData.getSchoolRank() > importData.getClassRank()) {
                result.addWarning("校内排名应该大于等于班内排名");
            }
        }
    }
    
    /**
     * 验证单个排名
     */
    private void validateRanking(String rankingName, Integer ranking, DataValidationResult result) {
//        if (ranking != null) {
//            if (ranking <= 0) {
//                result.addError(rankingName + "必须为正数: " + ranking);
//            } else if (ranking > 10000) {
//                result.addWarning(rankingName + "异常高: " + ranking);
//            }
//        }

    }
    
    /**
     * 验证数据一致性
     */
    private void validateDataConsistency(NewExamScoreImportExcelVO importData, DataValidationResult result) {
        // 验证选科组合与成绩的一致性
        String subjectCombination = importData.getSubjectCombination();
        if (subjectCombination != null && !subjectCombination.trim().isEmpty()) {
            // 检查选科组合中提到的科目是否有对应成绩
            if (subjectCombination.contains("物理") && importData.getPhysicsOriginalScore() == null) {
                result.addWarning("选科组合包含物理但未找到物理成绩");
            }
            if (subjectCombination.contains("历史") && importData.getHistoryOriginalScore() == null) {
                result.addWarning("选科组合包含历史但未找到历史成绩");
            }
        }
        
        // 验证总分与各科目成绩的逻辑关系
        BigDecimal calculatedTotal = BigDecimal.ZERO;
        int subjectCount = 0;
        
        if (importData.getChineseOriginalScore() != null) {
            calculatedTotal = calculatedTotal.add(importData.getChineseOriginalScore());
            subjectCount++;
        }
        if (importData.getMathOriginalScore() != null) {
            calculatedTotal = calculatedTotal.add(importData.getMathOriginalScore());
            subjectCount++;
        }
        if (importData.getEnglishOriginalScore() != null) {
            calculatedTotal = calculatedTotal.add(importData.getEnglishOriginalScore());
            subjectCount++;
        }
        
        // 如果有总分且有科目成绩，检查是否合理
        if (importData.getTotalOriginalScore() != null && subjectCount > 0) {
            BigDecimal difference = importData.getTotalOriginalScore().subtract(calculatedTotal).abs();
            if (difference.compareTo(new BigDecimal("50")) > 0) {
                result.addWarning("总分与各科目成绩之和差异较大，请检查数据准确性");
            }
        }
    }
    
    /**
     * 数据验证结果类
     */
    public static class DataValidationResult {
        private final List<String> errors = new ArrayList<>();
        private final List<String> warnings = new ArrayList<>();
        private final List<String> infos = new ArrayList<>();
        
        public void addError(String message) {
            errors.add(message);
        }
        
        public void addWarning(String message) {
            warnings.add(message);
        }
        
        public void addInfo(String message) {
            infos.add(message);
        }
        
        public boolean hasErrors() {
            return !errors.isEmpty();
        }
        
        public boolean hasWarnings() {
            return !warnings.isEmpty();
        }
        
        public List<String> getErrors() {
            return new ArrayList<>(errors);
        }
        
        public List<String> getWarnings() {
            return new ArrayList<>(warnings);
        }
        
        public List<String> getInfos() {
            return new ArrayList<>(infos);
        }
        
        public boolean isValid() {
            return errors.isEmpty();
        }
        
        public String getSummary() {
            StringBuilder sb = new StringBuilder();
            if (!errors.isEmpty()) {
                sb.append("错误: ").append(errors).append("; ");
            }
            if (!warnings.isEmpty()) {
                sb.append("警告: ").append(warnings).append("; ");
            }
            if (!infos.isEmpty()) {
                sb.append("信息: ").append(infos);
            }
            return sb.toString();
        }
    }
}